//
//  NetWorkSharedTools.m
//  EasyToTesco2.0
//
//  Created by 袖手旁觀 on 16/6/9.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "NetWorkSharedTools.h"
#import <CommonCrypto/CommonDigest.h>
#import <JDStatusBarNotification.h>

@implementation NetWorkSharedTools


//static NSString * const NewsBoardBaseURLString = @"http://www.dev.hzouxun.com";

static NSString * const NewsBoardBaseURLString = @"https://app.api.kw.hzouxun.com";

static NetWorkSharedTools *_instance;
+ (instancetype)sharedNetWorkTools{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] initWithBaseURL:[NSURL URLWithString:NewsBoardBaseURLString]];
        
        _instance.responseSerializer = [AFHTTPResponseSerializer serializer];
        _instance.requestSerializer.timeoutInterval = 10.f;
        _instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
        _instance.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"POST", @"GET", @"HEAD"]];
    });
    
    return _instance;
}

- (void)objectWithURLDict:(NSDictionary *)URLDict AndMenthodName:(NSString *)MenthodNameString completeBlock:(CompleteBlock)completeBlock {
    
    
    [self POST:MenthodNameString parameters:URLDict progress:^(NSProgress * _Nonnull uploadProgress) {
//        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        id result = [self toArrayOrNSDictionary:responseObject];

        if (completeBlock) {
            completeBlock(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"错误代码%zd",error.code);
        
        //无网 -1009  超时-1001
        [self errorNotificationStatusCode:[NSString stringWithFormat:@"%zd",error.code]];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_netWork_error object:nil];
        
    }];

}

- (void)GetObjectWithURLDict:(NSDictionary *)URLDict AndMenthodName:(NSString *)MenthodNameString completeBlock:(CompleteBlock)completeBlock {
    
    [self GET:MenthodNameString parameters:URLDict progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSString *string =  [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
//        NSLog(@"%@",task);
//        NSLog(@"%@",string);
        id result = [self toArrayOrNSDictionary:responseObject];
//        NSLog(@"%@",result);
        if (completeBlock) {
            completeBlock(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"%@",error);
//         NSLog(@"错误代码%zd",error.code);
        [self errorNotificationStatusCode:[NSString stringWithFormat:@"%zd",error.code]];
    }];
}


- (void)errorNotificationStatusCode:(NSString *)error_code
{//无网 -1009  超时-1001
    if ([error_code isEqualToString:@"-1001"]) {
        [JDStatusBarNotification showWithStatus:@"当前网络不佳,请稍后再试!" dismissAfter:5.f styleName:JDStatusBarStyleWarning];
    }else if ([error_code isEqualToString:@"-1009"]){
        [JDStatusBarNotification showWithStatus:@"当前无网络连接,请检查您的网络设置!" dismissAfter:5.f styleName:JDStatusBarStyleWarning];
    }
}

/**
 *  返回数据反序列化
 */
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}

/**
 *  32位MD5加密  小写x对应小写密文 大写X对应大写密文
 */
- (NSString *)getMd5_32Bit_String:(NSString *)srcString{
    const char *cStr = [srcString UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest );
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [result appendFormat:@"%02x", digest[i]];
    
    return result;
}

/**
 *  时间戳
 */
- (NSString *)DateFormatterWithNowDate {
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    formatter.dateFormat = @"yyyyMMddHHmmss";
    
    NSString *res = [formatter stringFromDate:date];
    
    return res;
}

@end
